package com.study.www.utils;

import com.study.www.config.SpringUtils;
import com.study.www.enums.JobTypeEnum;
import com.study.www.model.JobConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * @Description: :
 * @date :Create in  2018/2/26- 15:55
 * @Version: V1.0
 * @Modified By:
 **/
public class TaskUtils {

    private static final Logger log= LoggerFactory.getLogger(TaskUtils.class);


    public static void invokMethod(JobConfig config){
        Object obj=null;
        Class clazz=null;
        String jobCode=config.getJobType();
        JobTypeEnum targetJob= JobTypeEnum.findByJobCode(jobCode);
        //通过Spring上下文去找 也有可能找不到
        try {
            obj= SpringUtils.getBean(targetJob.getClazz());
            if(obj==null){
                throw new RuntimeException("spring容器没有该bean:"+targetJob.getClazz());
            }
            clazz = targetJob.getClazz();
        }catch (Exception e){
            log.error("ERROR:TaskUtils is Bean Create please check the classpath is`t right or not");
            throw  new RuntimeException("ERROR:TaskUtils is Bean Create please check the classpath is`t right or not");
        }
        Method method=null;
        //获得方法名
        try {
            method = clazz.getDeclaredMethod(targetJob.getMethodName(),JobConfig.class);
        } catch (NoSuchMethodException e) {
            log.error("ERROR:TaskUtils is Bean the method Create please check the methodName is`t right or not");
            throw new RuntimeException("ERROR:TaskUtils is Bean the method Create please check the methodName is`t right or not");
        }
        //方法执行
        try {
            method.invoke(obj,config);
        } catch (Exception e) {
            log.error("ERROR:TaskUtils is Bean the method Create please check the methodName is`t right or not");
            throw new RuntimeException("ERROR:TaskUtils is Bean the method execute please check the methodName is`t right or not");
        }

    }
}
